<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/3/15 11:34
 * Desc:
 */

namespace App\Http\Controllers\Admin;

use App\Facades\Code;
use App\Http\Controllers\BaseAdminController;
use App\Lib\Common;
use App\Lib\Enum\Params;
use App\Lib\Enum\ValRule;
use App\Lib\Logger;
use App\Lib\Validates;
use App\Models\Admin\Permission;
use App\Rules\CheckRule;
use App\Service\AuthService;
use Illuminate\Http\Request;

class PermissionController extends BaseAdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $permission = (new AuthService())->getPermission($request->all());
        //结果处理
        $result = !$permission->isEmpty() ? $this->success($permission) : $this->error(80000, "没有权限");
        return view("admin.permission.index", ["error" => $result["error"], "permissions" => $result["data"],"group"=>Code::getItemsByCode('PERMISSION_GROUP')]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $permission = (new AuthService())->getPermission(["flag"=>"select"]);
        $permission = Common::getTree($permission);
        //处理顶级栏目
        array_unshift($permission,["id"=>0,"parent_id"=>0,"name"=>"顶级栏目","children"=>[]]);
        return view("admin.permission.create",['permissions'=>json_encode($permission)]);
    }

    //获取数据
    public function getSelect() {
        $permission = (new AuthService())->getPermission(["flag"=>"select"]);
        $permission = Common::getTree($permission);
        //处理顶级栏目
        array_unshift($permission,["id"=>0,"parent_id"=>0,"name"=>"顶级栏目","children"=>[]]);
        return $permission;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $params = (new CheckRule($request->all()["data"], ValRule::SCOPE, ValRule::SCOPE_MSG))->check(1);
        $result = (new AuthService())->store($params["data"], getCurrentSiteId());
        //处理返回结果
        if (is_array($result) && array_key_exists("flag", $result)) {
            return $this->reRoute($result["route"]);
        }
        if (is_array($result) && array_key_exists("error", $result) && $result["error"] > 0) {
            return $this->error($result["error"], $result["msg"]);
        }
        if(!empty($result)){
            //将新加权限自动分配给超级管理员
            if($params["data"]["guard_name"]=="system"){
                (new AuthService())->assignAdmin([$params["data"]["name"]]);
            }
            $this->log(Logger::LOG_LEVEL_INFO,Logger::PERMISSION,'store','添加权限'.$params["data"]['name'].'成功',$result);
            return $this->success($result, "添加成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::PERMISSION,'store','添加权限'.$params["data"]['name'].'失败',['error'=>70000]);
        return $this->error(70000, "添加失败");
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show(Permission $permission) {
        $result = (new AuthService())->getInfoPer($permission);
        return view("admin.permission.show", ['permission' => $result["data"], 'error' => $result["error"]]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.permission.index", "id必须是正整数", "error");
        }
        $data = (new AuthService())->getOnePer($id);
        $result = !empty($data) ? $this->success($data) : $this->error(80000, "没有权限");
        $permission = (new AuthService())->getPermission(["flag"=>"select"]);
        $permission = Common::getTree($permission);
        //处理顶级栏目
        array_unshift($permission,["id"=>0,"parent_id"=>0,"name"=>"顶级栏目","children"=>[]]);
        return view("admin.permission.edit", ['permission' => $result["data"],'error' => $result["error"],'permissions'=>json_encode($permission)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.permission.index", "id必须是正整数", "error");
        }
        //修改
        $data = $request->all()["data"];
        $result = (new AuthService())->change($data, $id);
        //处理返回结果
        if (is_array($result) && array_key_exists("flag", $result)) {
            return $this->reRoute($result["route"]);
        }
        if (is_array($result) && array_key_exists("error", $result) && $result["error"] > 0) {
            return $this->error($result["error"], $result["msg"]);
        }
        if(!empty($result)){
            $this->log(Logger::LOG_LEVEL_INFO,Logger::PERMISSION,'update','修改权限'.$data['name'].'的信息成功',[]);
            return $this->success("", "更新成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::PERMISSION,'update','修改权限'.$data['name'].'的信息失败',['error'=>80000]);
        return $this->error(80000, "更新失败");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {

    }

    /**
     * 权限可操作状态
     */
    public function status(Request $request) {
        $parmas = $request->all()["data"];
        $check = Validates::isPositiveInteger($parmas["id"]);
        if (!$check) {
            return $this->tempNotice("admin.permission.index", "id必须是正整数", "error");
        }
        //开启关闭
        $result = (new AuthService())->noOroff($request->all()["data"]);
        if(!$result){
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::PERMISSION,'status','修改权限编号为'.$parmas['id'].'的状态失败',['error'=>80000]);
            return $this->error(80000, "状态修改失败");
        }
        $this->log(Logger::LOG_LEVEL_INFO,Logger::PERMISSION,'status','修改权限编号为'.$parmas['id'].'的状态成功',[]);
        return $this->success("", "状态修改成功");
    }

    /**
     * 检查输入路由
     */
    public function check_route(Request $request) {
        //验证
        $params = (new CheckRule($request->all()["data"], ValRule::ROUTENAME, ValRule::ROUTENAME_MSG))->check(1);
        if ($params["error"] > 0) {
            return $params;
        }
        if (array_key_exists("type", $params["data"]) && $params["data"]["type"] == 1) {
            return $this->success("", "路由可以添加", 2);
        }
        //验证
        $flag = (new AuthService())->checkRoute($params["data"]["name"]);
        return $this->reRoute($flag);
    }
}
